import { Injectable } from '@nestjs/common';
import { generateUniqueSixDigitNumber } from 'src/utils';
import { UserRepository } from './user.repository';
import { Response } from 'src/utils/response';
import { UserRegisterDto } from './dto/user-register.dto';
import { UserLoginDto } from './dto/user-login.dto';

@Injectable()
export class UserService {
  constructor(private readonly userRepository: UserRepository) {}

  // 注册
  async registerService(data: Partial<UserRegisterDto>) {
    try {
      if (!data.email) {
        return Response.error({
          message: 'email is required',
        });
      }
      if (!data.password) {
        return Response.error({
          message: 'password is required',
        });
      }
      // 查看是否有重复账号
      const user = await this.userRepository.findOneRepository({
        account: data.email,
      });
      if (user) {
        return Response.error({
          message: '该账号已存在',
        });
      }
      // let entity: any = addTimeFields(data);
      const entity: any = {
        ...data,
        account: data.email,
        nickName: `用户${generateUniqueSixDigitNumber()}`,
        state: '1',
      };
      const result = await this.userRepository.registerRepository(entity);
      if (!result) {
        return Response.error({
          message: '注册失败',
        });
      }
      return Response.success({ message: '注册成功' });
    } catch (e) {
      return Response.error({ message: e });
    }
  }

  // 登录
  async loginService(data: UserLoginDto) {
    try {
      const user = await this.userRepository.loginRepository(data);
      if (!user) {
        return Response.error({
          message: '该用户未注册',
        });
      }
      if (user.password !== data.password) {
        return Response.error({
          message: '账号或密码错误',
        });
      }
      return Response.success({ message: '登录成功', data: user });
    } catch (e) {
      return Response.error({ message: e });
    }
  }

  // 查询用户详情信息
  async queryUserDetail(ids: number[]) {
    return await this.userRepository.findRepository({ ids });
  }
}
